package br.edu.ufra.login;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

@SuppressWarnings("serial")
public class ControleAcessoListener2 implements PhaseListener {
	public void afterPhase(PhaseEvent event) {
	}
	
	//executa antes de qualquer renderizar ao usuario
	public void beforePhase(PhaseEvent event) {
		FacesContext context = FacesContext.getCurrentInstance();
		String pagAtual = context.getViewRoot().getViewId();
		//System.out.println("View ID:" + pagAtual);
		
		//verifica is conteudo protegido
		if (pagAtual.equals("/hello.jsp")){
			Application app = context.getApplication();
			
			ControleAutenticacao caut = (ControleAutenticacao)
							app.evaluateExpressionGet(context,
							"#{ControleAutenticacao}",
							ControleAutenticacao.class);
			
			// verifica se o usuario esta logado								
			if ( ! caut.isUsuarioLogado() ) {
				ViewHandler viewHandler = app.getViewHandler();
				UIViewRoot viewRoot = viewHandler.createView(context,
														"/login.jsp");
				context.setViewRoot(viewRoot);
			}
		}
	}
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}
}
